package com.jn.erp.web.api.student.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.web.api.course.entity.TCourseOrder;
import com.jn.erp.web.api.course.mapper.TCourseOrderMapper;
import com.jn.erp.web.api.institution.entity.vo.EmployeeVo;
import com.jn.erp.web.api.student.entity.*;
import com.jn.erp.web.api.student.entity.dto.EnrollmentStuDto;
import com.jn.erp.web.api.student.entity.dto.StudentBaseInfoDTO;
import com.jn.erp.web.api.student.entity.dto.StudentRenewalDto;
import com.jn.erp.web.api.student.entity.vo.TStudentCourseVo;
import com.jn.erp.web.api.student.mapper.StudentContactRecordMapper;
import com.jn.erp.web.api.student.mapper.StudentCourseMapper;
import com.jn.erp.web.api.student.mapper.StudentMapper;
import com.jn.erp.web.api.student.service.*;
import com.jn.erp.web.api.student.utils.BizException;
import com.jn.erp.web.api.student.utils.UserAuthUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

import static com.jn.erp.security.utils.SecurityUtils.getUserId;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Resource
    private StudentClassService studentClassService;

    @Autowired
    private StudentCourseMapper studentCourseMapper;

    @Autowired
    private StudentUserService studentUserService;
    @Autowired
    private StudentContactsUserService studentContactsUserService;


    @Autowired
    private StudentContactRecordMapper studentContactRecordMapper;

    @Autowired
    private TCourseOrderMapper tCourseOrderMapper;

    @Autowired
    StudentCourseServiceImpl studentCourseServiceImpl;

    @Override
    public List<Student> getList(Student student) {

        // 4是全部
        // 本周新增
        LocalDate localDate = LocalDate.now();
        if (student.getType().equals("1")) {
            LocalDate sTime = localDate.with(DayOfWeek.MONDAY);
            LocalDate eTime = localDate.with(DayOfWeek.SUNDAY);
            student.setSTime(sTime);
            student.setETime(eTime);
            //本月新增
        } else if (student.getType().equals("2")) {
            LocalDate sTime = localDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate eTime = localDate.with(TemporalAdjusters.lastDayOfMonth());
            student.setSTime(sTime);
            student.setETime(eTime);
            // 今日新增
        } else if (student.getType().equals("3")) {
            student.setSTime(localDate);
            student.setETime(localDate);
            // 回收站 delete = 1
        } else if (student.getType().equals("5")) {
            student.setDeleted(1);
        } else if (student.getStage() != null && student.getStage().equals(1) && student.getMine().equals("1")) {
            student.setCreator(getUserId());
        }
        List<Student> rows = studentMapper.getList(student);
        // 如果是历史学员 加上这个学员每个课的剩余课时
        for (Student row : rows) {
            if (row.getStage() == 5) {
                // 这个学生的所有订单
                List<StudentCourse> studentCourse = studentCourseMapper.selectOrder(row.getId());
                row.setStudentCourseList(studentCourse);
            }
        }
        return rows;
    }

    @Override
    public boolean delete(List<Long> ids) {
        if (this.removeByIds(ids)) {
            studentClassService.deleteClassStudent(ids);
            return true;
        }
        return false;
    }

    @Override
    public String selCount(EmployeeVo employeeVo) {
        return studentMapper.selNum(employeeVo);
    }

    @Override
    public List<EnrollmentStuDto> enrollmentList(EnrollmentStuDto student) {

        List<EnrollmentStuDto> list = studentMapper.enrollmentList(student);

        for (EnrollmentStuDto dto : list) {
           Integer i = studentCourseMapper.selAmountTotal(dto.getStudentId());
           Integer l = studentCourseMapper.selLessonTotal(dto.getStudentId());

            // 如果没结课
            if (dto.getExhausted() == 1) {
                // 剩余课时 总-消耗-退课
                int remainderLesson = l - dto.getCountLessonComplete() - dto.getCountLessonRefund();
                // 课消金额 = 单价*已上课次
                TCourseOrder s = tCourseOrderMapper.selectByStuId(dto.getStudentId());
                if (s == null) {
                    // 课消金额 = 0
                    BigDecimal spendAmount = new BigDecimal(0);
                    // 剩余课消金额 = 折扣价(总) - 课消金额
                    BigDecimal remainderAmount = new BigDecimal(i).subtract(spendAmount);
                    dto.setRemainderLesson(remainderLesson);
                    dto.setSpendAmount(spendAmount);
                    dto.setRemainderAmount(remainderAmount);
                } else {
                    // 课消金额 折扣价/购买总课次(总)*实扣课时（总）
                    BigDecimal spendAmount = dto.getDiscountAmount().divide(new BigDecimal(dto.getCountLessonTotalNormal()), BigDecimal.ROUND_CEILING).multiply(new BigDecimal(s.getClassHourPayNormal()));
//                    BigDecimal spendAmount = dto.getUnitPrice().multiply(new BigDecimal(s.getClassHourPayNormalTotal()));
                    // 剩余课消金额 = 折扣价(总) - 课消金额
                    BigDecimal remainderAmount =  new BigDecimal(i).subtract(spendAmount);
                    dto.setRemainderLesson(remainderLesson);
                    dto.setSpendAmount(spendAmount);
                    dto.setRemainderAmount(remainderAmount);
                }
            }
            //如果结课了
            else if (dto.getExhausted() == 0) {
                dto.setRemainderLesson(0);
                dto.setRemainderAmount(BigDecimal.valueOf(0));
            }

        }
        return list;
    }


    @Override
    public boolean changeStage(Long id, Integer stage, boolean force) {
        if (stage == 5) {
            Student stu = this.getById(id);
            //查学员总剩余多少课时
//        BigDecimal remaining = studentCourseService.getTotalLessonRemainingCount(stu.getId());
//        if (5 == stage && remaining != null) {
//            if (force) {
//                throw new BizException(stu.getName() + "的课次有剩余，无法结业");
//            }
//        }
            //        if (5 == stage) {
//            stu.setGraduationDate(LocalDate.now());
//        }
            return this.updateById(stu);

        } else {
            // 转为线索
            UpdateWrapper<Student> up = new UpdateWrapper<>();
            up.eq("id", id);
            up.set("stage", stage);
            up.set("counselor_id", null);
            up.set("management_id", null);
            return this.update(up);
        }

    }

    @Override
    public Long saveOrUpdateByDTO(StudentBaseInfoDTO dto) {
        if (StringUtils.isBlank(dto.getName())) {
            throw new BizException("学生姓名须提供一个");
        }

        StudentUser user = studentUserService.existOrCreate(dto.getMobile(), dto.getSchoolId());
        // id == null 创建新学员
        Long userId = UserAuthUtil.getCurrentUserId();
        if (dto.getCounselorId() == null) {
            dto.setCounselorId(userId);
        }
        Student student = new Student();
        BeanUtils.copyProperties(dto, student);
        student.setUserId(user.getId());
        student.setCreator(dto.getCreator());
        // 学生来源
        student.setJoinWay(dto.getJoinWay());
        if (dto.getId() == null) {
            student.setAddTime(LocalDateTime.now());
            student.setStage(1);
        } else {
            student.setStage(dto.getStage());
            student.setEditTime(LocalDateTime.now());
        }
        this.saveOrUpdate(student);
        user.setFamilyRel(student.getFamilyRel());
        studentUserService.updateById(user);
        return student.getId();
    }

    public List<Student> listByUid(Long userId) {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        return list(qw);

    }


    @Override
    public Student getStudent(Student student) {
        Student reStudent = studentMapper.getStudent(student);
        //获取默认
        StudentUser de = new StudentUser();
        de.setFamilyRel(reStudent.getFamilyRel());
        de.setMobile(reStudent.getMobile());
        reStudent.setDefaultUser(de);
        //获取备选
        QueryWrapper<StudentContactsUser> qw = new QueryWrapper<>();
        qw.eq("is_backup", 1);
        qw.eq("student_id", reStudent.getId());
        StudentContactsUser one = studentContactsUserService.getOne(qw);
        if (one != null) {
            StudentUser bu = new StudentUser();
            bu.setFamilyRel(one.getFamilyRel());
            QueryWrapper<StudentUser> qwu = new QueryWrapper<>();
            qwu.eq("id", one.getUserId());
            StudentUser one1 = studentUserService.getOne(qwu);
            if (one1 != null) {
                bu.setMobile(one1.getMobile());
            }
            reStudent.setBackupUser(bu);
        }
        return reStudent;
    }

    @Override
    public Student applicationOne(Student student) {
        Student stu = studentMapper.applicationOne(student);
        String courseName = stu.getCourseName();
        if (StringUtils.isEmpty(stu.getCourseName())) {
            stu.setCourses(null);
        } else {
            String[] strArray = courseName.split(",");
            stu.setCourses(strArray);
        }
        TCourseOrder s = tCourseOrderMapper.selectByStuId(student.getId());
        if (s != null) {
            BigDecimal spendAmount = stu.getUnitPrice().multiply(new BigDecimal(s.getClassHourPayNormalTotal()));
            stu.setSpendAmount(spendAmount);
        } else {
            stu.setSpendAmount(new BigDecimal(0));
        }
        return stu;
    }


    @Override
    public Student deleteClue(Student student) {
        Student stu = studentMapper.selectById(student.getId());
        // 放入回收站
        if (student.getType().equals("1")) {
            stu.setDeleted(1);
            stu.setDeletePeopleId(getUserId());
            stu.setDeleteReason(student.getDeleteReason());
            stu.setEditTime(LocalDateTime.now());
            stu.setDeleteTime(LocalDateTime.now());
            studentMapper.updateById(stu);

            // 彻底删除
        } else if (student.getType().equals("2")) {
            if (stu.getStage() == 1 && stu.getDeleted() == 1) {
                studentMapper.deleteById(stu);
            }
            // 复原
        } else if (student.getType().equals("3")) {
            if (stu.getDeleted() == 1) {
                // 如果是跟进学员 把跟进记录的数据删掉
                if (stu.getStage() == 3) {
                    StudentContactRecord studentContactRecord = studentContactRecordMapper.selOne(student.getRecordId());
                    studentContactRecord.setDeleted(0);
                    studentContactRecordMapper.updateById(studentContactRecord);
                }
                stu.setDeleted(0);
                stu.setEditTime(LocalDateTime.now());
                studentMapper.updateById(stu);
            }
        }
        return null;
    }


    @Override
    public void getCounselor(Student student) {
        Long orgId = 0l;
        boolean saveRecord = true;
        if (student.getManagementId() != null) {
            saveRecord = false;
        }
        List<Long> ids = student.getIds();
        for (Long id : ids) {
            Student stu = studentMapper.selectById(id);
            orgId = stu.getOrgId();
//            1, 意向学员 2, 在学学员 3 跟进学员 4.报读学员 5.历史学员
            if (stu.getStage() == 1) {
                // 分配跟进人
                stu.setCounselorId(student.getCounselorId());
                stu.setStage(3);
                //分配学管师
                stu.setManagementId(student.getManagementId());
                stu.setType("1");
                studentMapper.updateById(stu);

            } else {
                // 除了线索学员分配跟进人变成跟进管理， 其他的学员状态不变
                // 分配跟进人
                stu.setCounselorId(student.getCounselorId());
                //分配学管师
                stu.setManagementId(student.getManagementId());
                stu.setType("2");
                studentMapper.updateById(stu);
            }
            if (saveRecord) {
                // 添加一条跟进记录
                StudentContactRecord studentContactRecord = new StudentContactRecord();
                studentContactRecord.setCreator(getUserId());
                //  默认跟进时间
                studentContactRecord.setAddTime(LocalDateTime.now());
                studentContactRecord.setStudentId(stu.getId());

                //分配跟进人 在读报读中记录添加默认，跟进阶段-》更新跟进人）
                //跟进时间(默认操作时间)
                studentContactRecord.setContactTime(LocalDate.now());
                //跟进方式(其他)
                studentContactRecord.setState("5");
                //跟进阶段(更新跟进人)
                studentContactRecord.setPhase("10");
                studentContactRecord.setOrgId(orgId);
                studentContactRecordMapper.insert(studentContactRecord);
            }

        }
    }


    //////////////////////////统一新建线索/////////////////////////////////////////////
    @Override
    public Long studentUnifysaveOrUpdateByDTO(StudentBaseInfoDTO dto) {
        Student student = new Student();
        try {

            StudentUser defaultUser = dto.getDefaultUser();
            if (StringUtils.isBlank(dto.getName()) && defaultUser != null && StrUtil.isNotBlank(defaultUser.getMobile())) {
                throw new BizException("学生姓名须提供一个，且有关联手机号");
            }
            defaultUser.setOrgId(dto.getOrgId());
            defaultUser = studentUserService.existOrCreate(defaultUser);
            StudentUser backupUser = dto.getBackupUser();
            if (backupUser != null && StrUtil.isNotBlank(backupUser.getMobile())) {
                backupUser.setOrgId(dto.getOrgId());
                backupUser = studentUserService.existOrCreate(backupUser);

            }
// id == null 创建新学员
            Long userId = UserAuthUtil.getCurrentUserId();
            if (dto.getCounselorId() == null) {
                dto.setCounselorId(userId);
            }
            BeanUtils.copyProperties(dto, student);
            student.setUserId(defaultUser.getId());
            student.setCreator(dto.getCreator());
            // 学生来源
            student.setJoinWay(dto.getJoinWay());
            student.setAddTime(LocalDateTime.now());
            student.setFamilyRel(defaultUser.getFamilyRel());
            // 新加的线索学员 配置是1
            student.setCofId(1);
            if (dto.getId() == null) {
                student.setStage(1);
            } else {
                student.setStage(dto.getStage());
            }
            this.saveOrUpdate(student);


            if (dto.getId() != null) {
                QueryWrapper<StudentContactsUser> qw = new QueryWrapper();
                qw.eq("student_id", dto.getId());
                studentContactsUserService.remove(qw);
            }
            List<StudentContactsUser> clist = new ArrayList<>();
            StudentContactsUser c = new StudentContactsUser();
            c.setStudentId(student.getId());
            c.setUserId(defaultUser.getId());
            c.setFamilyRel(defaultUser.getFamilyRel());
            c.setIsBackup(0);
            clist.add(c);
            if (backupUser != null) {
                StudentContactsUser cb = new StudentContactsUser();
                cb.setStudentId(student.getId());
                cb.setUserId(backupUser.getId());
                cb.setFamilyRel(backupUser.getFamilyRel());
                cb.setIsBackup(1);
                clist.add(cb);
            }
            studentContactsUserService.saveBatch(clist);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return student.getId();
    }


    @Override
    public TableDataInfo enrollmentListPage(EnrollmentStuDto student) {
        return null;
    }

    @Override
    public EnrollmentStuDto remainderCount(EnrollmentStuDto student) {
        EnrollmentStuDto enrollmentStuDto = new EnrollmentStuDto();
        // 如果没有结课
            student.setExhausted(1);
            EnrollmentStuDto e =tCourseOrderMapper.countMoney(student);
            // 剩余总课时
            int remainderLessonTotal = e.getCountLessonTotal() - e.getCountLessonComplete() - e.getCountLessonRefund();
            enrollmentStuDto.setRemainderLessonTotal(remainderLessonTotal);
            // 课消金额
            enrollmentStuDto.setRemainderAmountTotal(e.getDiscountAmount());
        return enrollmentStuDto;

    }

    @Override
    public List<Student> allStudent(Student student) {
        return studentMapper.allStudent(student);
    }

    @Override
    public List<Student> studentList(Student student) {
        return studentMapper.studentList(student);
    }

    @Override
    public String changeStageHisyory(Student student) {
        Student byId = studentMapper.selectById(student.getId());
        // 转为历史 添加历史原因和时间
        Student stu = this.getById(student.getId());
        //查学员总剩余多少课时
//        int remaining = studentCourseService.getTotalLessonRemainingCount(stu.getId());
//            if (remaining>0) {
//                throw new ServiceException("课次有剩余，无法转为历史");
//            }
        // 清空这个学员的数据
        TStudentCourseVo tStudentCourseVo = new TStudentCourseVo();
        tStudentCourseVo.setStudentId(student.getId());
        tStudentCourseVo.setEditor(getUserId());
        studentCourseServiceImpl.dealClassEnding(tStudentCourseVo,3);
        byId.setTurnHistoryDate(LocalDate.now());
        byId.setTurnHistoryReason(student.getTurnHistoryReason());
        byId.setStage(5);
        studentMapper.updateById(byId);
        return "成功";
    }

    @Override
    public String selManageCount(EmployeeVo employeeVo) {
        return studentMapper.selManageCount(employeeVo);
    }

    @Override
    public List<StudentRenewalDto> alertsList(StudentRenewalDto studentRenewalDto) {
         List<StudentRenewalDto> stu =studentMapper.alertsList(studentRenewalDto);
         // 学生的全部课时
        return stu;
    }


}
